package com.sky.task;


import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.Schedules;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    @Scheduled(cron = "0 * * * * ? ")   // 每分钟执行一次
    public void processOutTimeOrder() {
        log.info("处理超时订单: {}", LocalDateTime.now());
        //1. 查询超时订单
        LocalDateTime localDateTime = LocalDateTime.now().minusMinutes(15);
        List<Orders> ordersList = orderMapper.selectOutTimeOrder(Orders.PENDING_PAYMENT, localDateTime);

        if (!ordersList.isEmpty()){
            // 2.设置订单状态为已取消
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("超时未支付，自动取消");
                orderMapper.updateOrder(orders);
            }
        }

    }


    @Scheduled(cron = "0 0 1 * * ? ")   // 每日凌晨一点执行一次
    public void autoCompleteOrder(){
        log.info("自动完成订单: {}", LocalDateTime.now());
        //1. 查询未完成的订单（正在派送中）
        LocalDateTime localDateTime = LocalDateTime.now().minusHours(1);
        List<Orders> ordersList = orderMapper.selectOutTimeOrder(Orders.DELIVERY_IN_PROGRESS, localDateTime);

        if (!ordersList.isEmpty()){
            // 2.设置订单状态为已完成
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.updateOrder(orders);
            }
        }
    }
}
